package com.utooo.bid.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Component
public class RedisChatMemoryStore implements ChatMemoryStore {
    private final RedisTemplate<String, Object> redisTemplate;
    public static final String KEY_PREFIX = "chat:memory:";

    public RedisChatMemoryStore(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public List<ChatMessage> getMessages(Object id) {
        String key = KEY_PREFIX + id.toString();
        Object json = redisTemplate.opsForValue().get(key);
        if (json == null) {
            return new ArrayList<>();
        }
        try {
            return ChatMessageDeserializer.messagesFromJson(String.valueOf(json));
        } catch (Exception e) {
            throw new RuntimeException("无法从 JSON 反序列化聊天消息", e);
        }
    }

    @Override
    public void updateMessages(Object id, List<ChatMessage> messages) {
        String key = KEY_PREFIX + id.toString();
        try {
            String json = ChatMessageSerializer.messagesToJson(messages);
            redisTemplate.opsForValue().set(key, json, 24, TimeUnit.HOURS);
        } catch (Exception e) {
            throw new RuntimeException("无法将聊天消息序列化为 JSON", e);
        }
    }

    @Override
    public void deleteMessages(Object id) {
        String key = KEY_PREFIX + id.toString();
        redisTemplate.delete(key);
    }
}